package cn.bird.storm.validated.paramcheck;

import cn.bird.storm.validated.paramcheck.tool.CheckNode;
import cn.bird.storm.validated.paramcheck.tool.CollCheckCondition;
import cn.hutool.core.util.StrUtil;

import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class AnnotationSupportUtil {

    /**
     * 非空校验
     */
    protected static void notEmpty(CollCheckCondition condition) {
        finalDo(builder -> builder.notEmpty(condition.getFieldName(), condition.getObject()));
    }


    /**
     * 非空校验
     */
    protected static void least(CollCheckCondition condition) {
        finalDo(builder -> builder.least(condition.getGroup(), condition.getFieldName(), condition.getObject()));
    }

    /**
     * 字符串范围校验
     */
    protected static void stringScope(CollCheckCondition condition) {
        finalDo(builder -> builder.stringScope(condition.getFieldName(),
                Optional.ofNullable(condition.getObject()).map(Object::toString).orElse(null),
                condition.getStringScope())
        );
    }

    /**
     * 自定义校验
     */
    protected static void customize(CollCheckCondition condition) {
        //如果第一个预留字段（即自定义方法 key）为空，返回
        if (StrUtil.isEmpty(condition.getReserve1())) {
            return;
        }
        //如果根据自定义方法 key 查不出来对应的方法，返回
        Map<String, Predicate<Object>> predicateMap =
                ParamCheckComponent.CUSTOMIZE_MAP.get();
        //如果 map 为空，或者根据自定义方法 key 查不出来对应的方法，返回
        if (predicateMap == null
                || predicateMap.get(condition.getReserve1()) == null) {
            return;
        }
        finalDo(builder -> builder.customize(condition.getFieldName(),
                condition.getObject(),
                predicateMap.get(condition.getReserve1()))
        );
    }
    /**
     * 最终要实现的逻辑
     */
    private static void finalDo(Consumer<ParameterCheckBuilder> consumer){
        Optional.ofNullable(ParamCheckComponent.getCheckNode())
                .map(CheckNode::getParameterCheckBuilder)
                .ifPresent(consumer);
    }

    public static void main(String[] args) {
        System.out.println((String)null);
    }
}
